<template>
  <div>
    <b-form class="mb-0" @submit="submit">
      <b-form-group label="用户名（30个字符以下）">
        <b-form-input v-model="form.username" placeholder="请输入用户名" :state="formRules.username" />
      </b-form-group>
      <b-form-group label="学员编号">
        <b-form-input v-model="form.studentId" placeholder="请输入学员编号" />
      </b-form-group>
      <b-form-group label="手机号">
        <b-form-input v-model="form.mobile" placeholder="请输入手机号" />
      </b-form-group>
      <b-form-group label="邮箱">
        <b-form-input v-model="form.email" placeholder="请输入邮箱" />
      </b-form-group>
      <b-form-group label="密码(8到20个字符)">
        <b-form-input v-model="form.password" type="password" placeholder="请输入密码" :state="formRules.password" />
      </b-form-group>
      <b-form-group label="请确认密码(与密码保持一致)">
        <b-form-input v-model="form.password2" type="password" placeholder="请确认密码" :state="formRules.password2" />
      </b-form-group>
      <b-button type="submit">提交</b-button>
    </b-form>
  </div>
</template>

<script>
import { register } from '~/api/user/index'
export default {
  name: 'SignUp',
  data() {
    return {
      form: {
        username: '',
        password: '',
        password2: '',
        email: '',
        mobile: '',
        studentId: ''
      },
      formRules: {
        username: null,
        password: null,
        password2: null
      }
    }
  },
  computed: {
    valid: function() {
      const ft = this.formRules
      return ft.username && ft.password2 && ft.password
    }
  },
  watch: {
    'form.username': function(userName) {
      if (userName && userName.length <= 30) {
        this.formRules.username = true
      } else {
        this.formRules.username = false
      }
    },
    'form.password': function(password) {
      if (password && password.length >= 8 && password.length <= 20) {
        this.formRules.password = true
        if (this.form.password2 && this.form.password2 !== password) {
          this.formRules.password2 = false
        }
      } else {
        this.formRules.password = false
      }
    },
    'form.password2': function(password2) {
      if (password2 && password2.length >= 8 && password2.length <= 20 && password2 === this.form.password) {
        this.formRules.password2 = true
      } else {
        this.formRules.password2 = false
      }
    }
  },
  methods: {
    submit(e) {
      e.preventDefault()
      if (this.valid) {
        register(this.form)
          .then(r => {
            this.$bvModal.msgBoxOk('注册成功', {}).then(r => {
              this.$router.push({
                path: '/'
              })
            })
          }).catch(e => {
            console.error('err', e)
            this.$bvModal.msgBoxOk(e.message, { bodyClass: 'error' })
          })
      } else {
        this.$bvModal.msgBoxOk('表单填写有误，请检查', { bodyClass: 'error' })
      }
    }
  }
}
</script>

<style scoped>
  .error {
    color: #bd2130;
  }
</style>
